package org.seven.jrdp.biz.sys.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.seven.jrdp.biz.sys.mapper.SysResMapper;
import org.seven.jrdp.biz.sys.mapper.SysRoleResMapper;
import org.seven.jrdp.biz.sys.model.SysRes;
import org.seven.jrdp.biz.sys.model.SysRoleRes;
import org.seven.jrdp.commons.exception.BizException;
import org.seven.jrdp.commons.model.TreeNode;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class SysResService {
	@Autowired
	private SysResMapper sysResMapper;
	@Autowired
	private SysRoleResMapper sysRoleResMapper;

	@Transactional(readOnly = true)
	public List<SysRes> find() {
		Example example = new Example(SysRes.class);
		example.orderBy("sort");
		return sysResMapper.selectByExample(example);
	}

	@Transactional(readOnly = true)
	public SysRes get(String id) {
		return sysResMapper.selectByPrimaryKey(id);
	}

	@CacheEvict(cacheNames = { "role", "mgt" }, allEntries = true)
	@Transactional
	public void insert(SysRes sysRes) {
		sysResMapper.insertSelective(sysRes);
	}

	@CacheEvict(cacheNames = { "role", "mgt" }, allEntries = true)
	@Transactional
	public void update(SysRes sysRes) {
		sysResMapper.updateByPrimaryKeySelective(sysRes);
	}

	@CacheEvict(cacheNames = { "role", "mgt" }, allEntries = true)
	@Transactional
	public void delete(String id) {
		Example example = new Example(SysRes.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("pid", id);
		if (sysResMapper.selectCountByExample(example) > 0) {
			throw new BizException("该资源下存在子资源，不允许删除");
		}
		sysResMapper.deleteByPrimaryKey(id);
		SysRoleRes sysRoleRes = new SysRoleRes();
		sysRoleRes.setResId(id);
		sysRoleResMapper.delete(sysRoleRes);
	}

	@Transactional(readOnly = true)
	public List<TreeNode> findTree() {
		return sysResMapper.findTree();
	}
}